<?php

namespace App\Models\V5;

use DB;

class CompanyModel
{


    /*
     * 添加企业
     * @param companyInfo 公司信息
     * */
    public function add_company(array $companyInfo)
    {
        do {
            $companySn = randStr(8);
            $oldInfo   = $this->get_company_info_by_sn($companySn);
        } while ($oldInfo != false);

        $companyInfo['company_sn']   = $companySn;
        $companyInfo['surplus_port'] = $companyInfo['vip_port'];
        $companyInfo['add_date']     = date_time();
        $result                      = DB::table('company')->insertGetId($companyInfo);
        return $result;
    }


    /**
     * 更新公司信息
     * @param array companyInfo 企业信息
     * @return Object
     * */
    public function update_company(array $companyInfo)
    {
        $companyId = $companyInfo['company_id'];
        if (empty($companyId) || $companyId <= 0) {
            return false;
        }
        $result = DB::table('company')->where('company_id', $companyId)->update($companyInfo);
        return $result;
    }


    /**
     * 删除公司
     * @param integer $companyId 公司ID
     * */
    public function delete_company($companyId)
    {
        DB::table('company')->where('company_id', $companyId)->update(['is_delete' => 1]);

        //删除公司部门
        DB::table('company_department')
            ->where('company_id', $companyId)
            ->where('is_delete', 0)
            ->update(['is_delete' => 2]);

        $readPartys = DB::table('read_party')
            ->where('company_id', $companyId)
            ->where('DeleteMark', 1)
            ->get();

        foreach ($readPartys as $read) {
            DB::table('read_party_member')
                ->where('read_party_id', $read->ReaParID)
                ->where('is_delete', 0)
                ->update(['is_delete' => 2]);
        }

        //将该公司的企业读书会删除
        DB::table('read_party')
            ->where('company_id', $companyId)
            ->where('DeleteMark', 1)
            ->update(['DeleteMark' => 2]);
    }

    /**
     * 获得公司列表
     * @param string $keywords 公司名称关键字
     * */
    public function get_company_list($keywords = '')
    {

        $companys = DB::table('company as a')
            ->leftJoin('memberinfo as b', 'b.UserID', '=', 'a.manager_user_id')
            ->select('a.*', 'b.UserName as mobile', 'b.YourName as manager')
            ->where('a.is_delete', 0);
        if ($keywords) {
            $companys = $companys->where('a.company_name', 'like', "%$keywords%");
        };
        $companys = $companys->paginate(10);
        return $companys;
    }


    /*
     * 获得公司详情
     * */
    public function get_company_info($companyid)
    {
        $companyInfo = DB::table('company')->where('company_id', $companyid)->first();
        return $companyInfo;
    }

    /**
     * 根据公司编号获取公司信息
     * @param string companySn  公司编号
     * @return object
     * */
    public function get_company_info_by_sn($companySn)
    {
        $companyInfo = DB::table('company')
            ->where('company_sn', $companySn)
            ->where('is_delete', 0)
            ->first();
        return $companyInfo ? $companyInfo : false;
    }

    /**
     * 通过公司名称获得公司信息
     * */
    public function get_company_info_by_name($companyName)
    {
        $companyInfo = DB::table('company')->where('company_name', $companyName)->where('is_delete', 0)->first();
        return $companyInfo ? $companyInfo : false;
    }

    /*
     * 更新 或 添加 部门
     * */
    public function update_department(array $departmentInfo)
    {
        $dpInfo         = $departmentInfo;
        $departmentId   = isset($dpInfo['department_id']) ? $dpInfo['department_id']    : 0;
        //检查这个部门是否已经添加过
        if($departmentId == 0)
        {
            $companyId  = isset($dpInfo['company_id'])      ? $dpInfo['company_id']     : 0;
            $readId     = isset($dpInfo['read_party_id'])   ? $dpInfo['read_party_id']  : 0;
            $dpName     = isset($dpInfo['department_name']) ? $dpInfo['department_name']: "";
            $hasDp      = DB::table('company_department')
                ->where('company_id',$companyId)
                ->where('read_party_id',$readId)
                ->where('department_name',$dpName)
                ->first();
            if($hasDp)
            {
                return "本读书会已存在".$dpName."这个部门";
            }
        }

        //修改 | 新增
        $table          = DB::table('company_department');
        if ($departmentId) {
            $result = $table->where("department_id", $departmentInfo)->update($departmentInfo);
        } else {
            $result = $table->insertGetId($departmentInfo);
        }
        return $result;
    }


    /**
     * 获取公司的部门
     * @param integer $companyId 公司ID
     * @param integer $readPartyId 读书会ID
     * @return array
     * */
    public function get_company_department($companyId,$readPartyId)
    {

        $db = DB::table('company_department');
        if($readPartyId > 0)
        {
            $db->where('read_party_id',$readPartyId);
        }
        $result = $db->where('company_id', $companyId)
            ->where('is_delete', 0)
            ->orderBy('sort')
            ->get();
        $result = $result ? $result : [];
        return $result;
    }

    /**
     * 获得部门信息
     * @param integer deparmentId 部门ID
     * @return object
     * */
    public function department_info($departmentId)
    {
        $info = DB::table('company_department')->where('department_id', $departmentId)->first();
        $info = $info ? $info : false;
        return $info;
    }


    /**
     * 删除部门
     * @param integer $departmentId 部门ID
     * */
    public function department_delete($departmentId)
    {
        $result = DB::table('company_department')->where('department_id', $departmentId)->delete();
        return $result;
    }


    /**
     * 使用企业端口数量
     * @param integer companyId  公司ID
     * @param integer portNuber  端口数量
     * @return boolean
     * */
    public function use_company_port($companyId, $portNumber)
    {

        $db          = DB::table('company')->where('company_id', $companyId);
        $companyInfo = $db->first();
        if ($portNumber > $companyInfo->surplus_port) { //端口数量不足
            return false;
        }
        $result = $this->reduce_company_port($companyId, $portNumber);
        $result = $result ? true : false;
        return $result;
    }


    /**
     * 增加端口 总的增加 剩余的也增加
     * @param integer $companyId 公司ID
     * @param integer $portNumber 端口数量
     *
     * */
    public function add_company_port($companyId, $portNumber)
    {
        $SQL = "UPDATE company
                  SET vip_port = vip_port + $portNumber,
                      surplus_port = surplus_port + $portNumber
                  WHERE company_id = $companyId";
        return DB::query($SQL);

    }


    /**
     * 恢复公司端口
     * */
    public function reset_company_surplus_port($companyId, $portNumber)
    {
        return DB::table('company')
            ->where('company_id', $companyId)
            ->increment('surplus_port', $portNumber);
    }


    /**
     * 减少端口
     * @param integer $companyId 公司ID
     * @param integer $portNumber 端口数量
     * */
    public function reduce_company_port($companyId, $portNumber)
    {
        return DB::table('company')
            ->where('company_id', $companyId)
            ->decrement('surplus_port', $portNumber);
    }


    /**
     * 添加公司雇员
     * @param integer $companyId 公司ID
     * @param integer $departmentId 部门ID
     * @param integer $userId 用户ID
     * @param string $job 工作
     * */
    public function add_company_member($companyId, $departmentId, $userId, $job = '')
    {
        $time   = date_time();
        $data   = [
            'company_id'    => $companyId,
            'department_id' => $departmentId,
            'user_id'       => $userId,
            'job'           => $job,
            'is_delete'     => 0,
            'release_time'  => $time,
            'add_time'      => $time
        ];
        $result = DB::table('company_user')->insert($data);
        return $result;
    }

    /**
     * 修改公司用户信息
     * @param integer $userId 用户ID
     * @param integer $companyId 公司ID
     * @param array $data 修改的数据
     *
     * */
    public function update_company_member($userId, $companyId, $data)
    {
        return DB::table('company_user')
            ->where('user_id', $userId)
            ->where('company_id', $companyId)
            ->update($data);
    }


    /**
     * 会员退出公司
     * @param integer $companyId 公司ID
     * @param integer userId 会员ID
     * */
    public function delete_company_member($companyId, $userId)
    {
        $this->update_company_member($userId, $companyId, ['is_delete' => 1]);
        //2.恢复公司的端口
        $this->reset_company_surplus_port($companyId, 1);
    }

    /**
     * 移动部门会员
     * @param integer $companyId 公司ID
     * @param integer $oldDepartmentId 原始部门ID
     * @param integer $newDepartmentId 新的部门ID
     * */
    public function move_department_member($companyId, $oldDepartmentId, $newDepartmentId)
    {
        DB::table('company_user')
            ->where('company_id', $companyId)
            ->where('department_id', $oldDepartmentId)
            ->update(['department_id' => $newDepartmentId]);
    }

    /**
     * 统计公司员工数量
     * */
    public function count_company_member($companyId)
    {
        return DB::table('company_user')
            ->where('is_delete', 0)
            ->where('company_id', $companyId)
            ->distinct('company_id', 'department_id')
            ->count();

    }


    /**
     * 获得公司员工
     * @param integer $companyId 公司ID
     * @param string $keywords 关键字
     * @param integer $length 每次获取的条数
     * */
    public function get_company_members($companyId, $keywords = '', $length = 20)
    {
        $colums  = [
            'a.job',
            'a.company_id',
            'b.States',
            'b.UserID',
            'b.MemEndTime',
            'b.personal_end_time',
            'b.YourName',
            'b.NickName',
            'b.UserName',
            'd.department_name'
        ];
        $members = DB::table('company_user as a')
            ->leftJoin('memberinfo as b', 'b.UserID', '=', 'a.user_id')
            ->leftJoin('company_department as d', 'd.department_id', '=', 'a.department_id')
            ->select($colums)
            ->where('a.company_id', $companyId)
            ->where('a.is_delete', 0);

        if ($keywords) {
            $members->where(function ($query) use ($keywords) {
                $query->where('b.UserName', 'like', "%$keywords%")
                    ->orWhere('b.NickName', 'like', "%$keywords%")
                    ->orWhere('b.YourName', 'like', "%$keywords%");
            });
        }

        $members = $members->paginate($length);
        return $members;
    }


    /**
     * 获得公司会员信息
     * @param integer $companyId 公司ID
     * @param integer $userId 用户ID
     * @return Object
     * */
    public function get_company_member_info($companyId, $userId)
    {
        $info = DB::table('company_user as a')
            ->leftJoin('company_department as b', 'b.department_id', '=', 'a.department_id')
            ->select('a.*', 'b.department_name')
            ->where('a.company_id', $companyId)
            ->where('a.user_id', $userId)
            ->first();
        return $info;
    }

    /**
     * 根据公司与个人获取这个人部门的信息
     * @param $companyId 公司的ID
     * @param $userId 用户的ID
     * @return mixed
     */
    public function get_company_many_member_info_by_companyId_and_userId($companyId, $userId)
    {
        $info = DB::table('company_user as cu')
            ->leftJoin('company_department as cd', 'cd.department_id', '=', 'cu.department_id')
            ->select('cu.*', 'cd.department_name')
            ->where(['cu.company_id' => $companyId, 'cu.user_id' => $userId, 'cu.is_delete' => 0])
            ->get();
        return $info;
    }


    /**
     * 检查公司是否存在某用户
     *
     * @param integer $companyId 公司ID
     * @param integer $userId 用户ID
     * @return Object
     * */
    public function company_exists_member($companyId, $userId)
    {
        $info = DB::table('company_user')
            ->where('company_id', $companyId)
            ->where('user_id', $userId)
            ->where('is_delete', 0)
            ->first();
        return $info ? true : false;
    }


    /**
     * 获得公司的读书会列表
     *
     * @param integer $companyId 公司ID
     *
     * */
    public function get_company_read_partys($companyId)
    {
        $readpartys = DB::table('read_party')
            ->where('DeleteMark', 1)
            ->where('company_id', $companyId)
            ->get();
        return $readpartys;
    }


   

    /**
     * 公司资源分类
     * @param int $companyId 公司ID
     * @param int $readPartyId 读书会ID
     * */
    public function get_company_source_type($companyId,$readPartyId)
    {
        $types = DB::table('company_source_type')
            ->select('id','type_name')
            ->where('company_id',$companyId)
            ->where(function($db) use ($readPartyId){
                $db->where('read_party_id',$readPartyId)
                ->orWhere('read_party_id',0);
            })
            ->where('deleted_at')
            ->orderBy('sort')
            ->get();
        return $types;
    }



    /**
     * 获取公司资源
     * @param int $companyId    公司ID
     * @param int $typeId       资源分类ID
     * @param int $readPartyId  读书会ID
     * */
    public function get_company_source($companyId,$typeId = 0,$readPartyId=0)
    {
        $colums = [
            'a.id',
            'a.type as type_id',
            'a.category',
            'a.title',
            'a.content',
            'a.description',
            'a.face_img',
            'a.view_times',
            'a.created_at',
            'b.type_name'
        ];
        $db     = DB::table('company_source as a')
            ->leftJoin('company_source_type as b','b.id','=','a.type')
            ->select($colums);


        if($companyId > 0)
        {
            $db->where(function($db) use ($companyId){

                $db->where('a.company_id',$companyId)
                    ->orWhere('a.company_id',0);
            });
            //$db->where('a.company_id',$companyId);
        }

        if($typeId > 0)
        {
            $db->where('a.type',$typeId);
        }

        if($readPartyId > 0)
        {
            $db->where(function($db) use ($readPartyId){
                $db->where('a.read_party_id',$readPartyId)->orWhere('a.read_party_id',0);
            });
        }

        $date    = current_date();
        $sources = $db->where('a.deleted_at')
                ->where('b.deleted_at')
                ->where('a.is_show',1)
                ->where('published_at',"<=",$date)
                ->paginate(10);

        $categorys = ['video'=>'视频','audio'=>'音频','article'=>'文章'];
        foreach($sources as $source)
        {
            $source->categoryName   = $categorys[$source->category];
            $source->face_img       = env('HOST')."/".$source->face_img;
        }
        return $sources;
    }


    /**
     * 公司资源详情
     * */
    public function get_source_detail($sourceId)
    {

        $colums = [
            'a.id',
            'a.type as type_id',
            'a.category',
            'a.title',
            'a.content',
            'a.description',
            'a.face_img',
            'a.view_times',
            'a.created_at',
            'b.type_name'
        ];
        $sourceDetail = DB::table('company_source as a')
            ->leftJoin('company_source_type as b','b.id','=','a.type')
            ->select($colums)
            ->where('a.id',$sourceId)
            ->where('a.deleted_at')
            ->where('a.is_show',1)
            ->first();

        $categorys = ['video'=>'视频','audio'=>'音频','article'=>'文章'];
        $sourceDetail->categoryName   = $categorys[$sourceDetail->category];
        $sourceDetail->face_img       = env('HOST')."/".$sourceDetail->face_img;
        return $sourceDetail;
    }

}